from datetime import timedelta

from flask import Blueprint, jsonify, request
from flask_jwt_extended import create_access_token, get_jwt_identity

from models import Account
from utils.auth_utils import check_password
from utils.res_result import make_response
from utils.role_required import role_required

auth = Blueprint('Auth', __name__)


@auth.route("/auth", methods=["GET", "POST"])
def login():
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    if not username:
        return make_response(code=400, message="Missing username parameter", status=400)
    if not password:
        return make_response(code=400, message="Missing password parameter", status=400)

    login_user = Account.query.filter_by(username=username).first()

    if login_user is None or username != login_user.username or check_password(login_user.password, password) is False:
        return make_response(code=401, message="Bad username or password", status=401)

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=username, expires_delta=timedelta(hours=24))
    return make_response(code=0, message="ok", data={"token": access_token}, status=200)


@auth.route("/api/getUserInfo", methods=["GET", "POST"])
@role_required()
def get_user_info():
    current_user = get_jwt_identity()
    user = Account.query.filter_by(username=current_user).first()

    roles = []
    for role in user.roles:
        if role.status == '1':  # 假设status='1'表示启用状态
            roles.append(RoleInfo(
                role_name=role.role_name.upper(),
                role_value=role.role_value.upper()
            ).to_dict())

    user_info = UserInfo(
        username=user.username,
        real_name=user.username,
        avatar='',
        desc='',
        home_path='/dashboard/analysis',
        # role全部大写
        roles=roles
    )
    return make_response(code=0, message="ok", data=user_info.__dict__, status=200)


class UserInfo:

    def __init__(self, username, real_name, avatar, desc, home_path, roles):
        self.username = username
        self.realName = real_name
        self.avatar = avatar
        self.desc = desc
        self.homePath = home_path
        self.roles = roles


class RoleInfo:

    def __init__(self, role_name, role_value):
        self.roleName = role_name
        self.value = role_value

    def to_dict(self):
        return {
            "roleName": self.roleName,
            "value": self.value
        }
